'use strict'

var Promise = require('bluebird')
var request = Promise.promisify(require('request'))

var prefix = 'https://api.weixin.qq.com/cgi-bin/'
var api = {
	accessToken: prefix + 'token?grant_type=client_credential'
}

function WeChat(opts) {
	var that = this
	this.appID = opts.appID
	this.appSecret = opts.appSecret
	this.getAccessToken = opts.getAccessToken
	this.saveAccessToken = opts.saveAccessToken

	this.getAccessToken().then(function(data) {
		try {
			data = JSON.parse(data)
		} catch(e) {
			return that.updateAccessToken()
		}

		if(that.isValidAccessToken(data)) {
			Promise.resolve(data)
		} else {
			return that.updateAccessToken()
		}
	}).then(function(data) {
		that.access_token = data.access_token
		that.expires_in = data.expires_in

		that.saveAccessToken(data)
	})
}
module.exports = WeChat.prototype.isValidAccessToken = function(data) {
	//如果三个参数任意一个不存在，则返回false
	if(!data || !data.access_token || !data.expires_in) {
		return false
	}

	var access_token = data.access_token
	var expires_in = data.expires_in
	var now = (new Date().getTime())

	//如果当前时间小于过期时间，则返回true，否则返回false
	if(now < expires_in) {
		return true
	} else {
		return false
	}
}

WeChat.prototype.updateAccessToken = function() {
	var appID = this.appID
	var appSecret = this.appSecret
	var url = api.accessToken + '&appid=' + appID + '&secret=' + appSecret
	//https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9fc2209dc4dcc20c&secret=b52c4157170b8f1d9fd1ebeb33051762
	//https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
	return new Promise(function(resolve, reject) {
		request({
			url: url,
			json: true
		}).then(function(res) {
			//console.log(res.body)
			var data = res.body

			var now = new Date().getTime()

			var expires_in = now + (data.expires_in - 20) * 1000

			data.expires_in = expires_in

			resolve(data)
		})
	})
}